<?php
/**
 * Description: 图片审核
 * Created by PhpStorm.
 * User: congyukun
 * Date: 2021/3/25
 * Time: 18:29
 */

namespace Beerus\Modules\Brand\Controllers;


use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\Brand\Extensions\Tools\BrandImageBatchCheck;
use Beerus\Modules\Brand\Extensions\Tools\BrandImageCheck;
use Beerus\Modules\Wiki\Controllers\AdmController;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\service\wiki\WikiBasic;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

class WikiBasicImagesController extends Controller
{
    public function imageList(Request $request, Content $content)
    {
        $brand_id = $request->input('brand_id');
        $store_id = $request->input('store_id');
        $image_status = $request->input("imgs_status");
        $id = $request->input("id");
        $page = $request->input("page") ?: 1;
        $pageSize = $request->input("per_page", 20);
        if (!$request->input('wiki_basic_type')) {
            $request->merge([
                'wiki_basic_type' => 1,
            ]);
        }
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $wikiBasicType = $request->input('wiki_basic_type');
        $where['LIMIT'] = $limit;
        $where['brand_id'] = $brand_id;
        $where['store_id'] = $store_id;
        $where['imgs_status'] = $image_status;
        $where['id'] = $id;
        $where['wiki_basic_type'] = $request['wiki_basic_type'];

        //获取品牌数据
        $basic_info = WikiBasic::getWikiList($where);
        $list = [];
        foreach ($basic_info['list'] as $row) {
            $row['imgs'] = mWikiBasic::formData($row['imgs']);
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list, $basic_info['total'], [
            'perPage' => $pageSize
        ]);

        $list = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $wikiBasicType) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) use ($wikiBasicType) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) use ($wikiBasicType) {
                        $filter->equal('wiki_basic_type', '门店/品牌')->select(mWikiBasic::WIKI_BASIC_TYPE);
                        if ($wikiBasicType == mWikiBasic::WIKI_BASIC_BRAND) {
//                            $filter->equal('brand_name', '品牌名称')->placeholder('请输入品牌名称');
                            $filter->equal('brand_id', '品牌ID')->placeholder('品牌ID');
                        }
                        if ($wikiBasicType == mWikiBasic::WIKI_BASIC_STORE) {
//                            $filter->equal('store_name', '门店名称')->placeholder('请输入门店名称');
                            $filter->equal('store_id', '门店ID')->placeholder('门店ID');
                        }
                    });
                    $filter->column(1 / 2, function ($filter) use ($wikiBasicType) {
                        $filter->equal('imgs_status', '审核状态')->select(WikiBasic::IMGS_STATUS);
                        $filter->equal('id', 'WIKI_ID')->placeholder('wiki_id');
                    });

                    $filter->expand();//默认展开
                });
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->tools(function (Grid\Tools $tools) {
                    $tools->batch(function (BatchActions $batch) {
                        $batch->disableDelete();
                        $batch->add('批量通过', new BrandImageBatchCheck(1));
                    });
                });
                $grid->column('id', 'ID');
                if ($wikiBasicType == mWikiBasic::WIKI_BASIC_BRAND) {
                    $grid->column('brand_id', '品牌ID');
                    $grid->column('brand_name', '品牌名称');
                }
                if ($wikiBasicType == mWikiBasic::WIKI_BASIC_STORE) {
                    $grid->column('store_id', '门店ID');
                    $grid->column('store_name', '门店名称');
                }
                $grid->column('imgs_status', '审核状态')->display(function () {
                    //图片状态：0：默认  1：已审核-通过  2：未审核  3：审核未通过
                    switch ($this->imgs_status) {

                        case WikiBasic::IMGS_STATUS_DONE:
                            $res = "已审核";
                            break;
                        case WikiBasic::IMGS_STATUS_WAIT:
                            $res = "未审核";
                            break;
                        default:
                            $res = "默认";
                            break;
                    }
                    return $res;
                });
                $grid->column('imgs', '图片')->display(function () {
                    $html = '';
                    foreach ($this->imgs as $row) {
                        $html .= '<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'1000px\', \'900px\'],content: \'' . $row['img'] . '\'});">
                                <img width="100px" height="100px" src="' . $row['img'] . '">
                            </a>';
                    }
                    return $html;
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->prepend('&nbsp;<a class="fa fa-edit" target="" href="' . url('/admin/brand/wiki/checklist?id=' . $actions->row->id) . '">审核</a>');
                });
            }
        );
        $tab = new Tab();
        $tab->addLink('品牌/门店wiki审核', url('/admin/brand/wiki/list'), false);
        $tab->addLink('品牌/门店wiki编辑待审核', url('/admin/brand/wiki/editAuditList'), false);
        $tab->add('品牌/门店wiki图片审核', $list->render(), true);
        $content->row($tab);
        return $content
            ->header('品牌/门店wiki图片审核列表')
            ->description(' ')
            ->breadcrumb(
                ['text' => '图片待审核列表']
            );
    }

    /**
     * 根据basic_id 获取图片列表
     * @param Request $request
     * @param Content $content
     * @return Content|\Illuminate\Http\JsonResponse
     */
    public function checkList(Request $request, Content $content)
    {
        $params = $request->all();
        $rules = [
            'id' => "required|integer",
        ];
        //验证参数
        $returnMsg = \Biz\tools\helper\Common::validatorRule($rules, $params);
        if ($returnMsg !== true) {
            $msg = [
                'message' => $returnMsg,
                'code' => 0,
            ];
            return response()->json($msg);
        }
        $basic_id = $params['id'];
        //获取配置图片
        $basic_images = mWikiBasic::get('imgs', ['id' => $basic_id]);
        $list = mWikiBasic::formData($basic_images);
        foreach ($list as $k => $item) {
            $list[$k]['id'] = $k;
        }
        $gridModel = new pGridDataModel($list);
        Admin::script($this->changeScript());
        $imgList = Admin::grid($gridModel,
            function (Grid $grid) use ($basic_id) {
                $grid->tools(function (Grid\Tools $tools) use ($basic_id) {
                    $tools->batch(function (BatchActions $batch) use ($basic_id) {
                        $batch->disableDelete();
                        $batch->add('通过', new BrandImageCheck(1, $basic_id));
                        $batch->add('拒绝', new BrandImageCheck(2, $basic_id));
                    });
                });
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->disableActions();
                $grid->disablePagination();


                $grid->column('id', 'ID');
                $grid->column('img_id', 'img_id');
                $grid->column('img', "图片")->image('', 360, 360);
                $grid->column('status', '审核状态')->display(function ($status) {
                    //图片状态：0：默认  1：已审核-通过  2：未审核  3：审核未通过
                    switch ($status) {
                        case 0:
                            $res = "默认";
                            break;
                        case 1:
                            $res = "通过";
                            break;
                        case 2:
                            $res = "待审核";
                            break;
                        case 3:
                            $res = "拒绝";
                            break;
                    }
                    return $res;
                });
            }
        );

        return $content
            ->row($imgList)
            ->header('图片待审核列表')
            ->description(' ')
            ->breadcrumb(
                ['text' => '图片待审核列表', 'url' => '/brand/wiki/imagelist'],
                ['text' => '图片审核']
            );
    }


    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function audit(Request $request)
    {
        try {
            $params = $request->all();
            $rule = [
                'ids' => "required",
                'action' => "required|integer",
            ];
            $returnMsg = AdmController::validatorRule($rule, $params);

            if ($returnMsg !== true) {
                throw new \UnexpectedValueException($returnMsg);
            }
            $basic_id = $params['basic_id'];
            $ids = $params['ids'];
            $action = $params['action'];
            $where['id'] = $basic_id;
            //获取原全部图片
            $imgs = mWikiBasic::get('imgs', $where);
            if (!$imgs) {
                throw new \UnexpectedValueException("不存在或已删除");
            }
            $imgs = json_decode($imgs, true);
            //1:通过
            $status = WikiBasic::WIKI_BASIC_IMAGE_STATUS_UNPASS;
            if ($action == 1) {
                $status = WikiBasic::WIKI_BASIC_IMAGE_STATUS_DONE;
            }
            //组合图片状态
            foreach ($imgs as $k => $img) {
                if (in_array($k, $ids, false)) {
                    $imgs[$k]['status'] = $status;
                }
            }
            $data['cover_img'] = '';
            //查找新的首图
            foreach ($imgs as $img) {
                if ($img['status'] == WikiBasic::WIKI_BASIC_IMAGE_STATUS_DONE) {
                    $data['cover_img'] = $img['img'];
                    break;
                }
            }
            $data['imgs'] = json_encode($imgs);
            $data['imgs_status'] = WikiBasic::IMGS_STATUS_DONE;

            WikiBasic::updateData($where, $data);
            $res_msg = [
                'title' => '操作成功',
                'code' => 200
            ];
        } catch (\UnexpectedValueException $e) {
            $res_msg = [
                'title' => $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        } catch (\Exception $e) {
            $res_msg = [
                'title' => '操作失败,',
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($res_msg);
    }

    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchAudit(Request $request)
    {
        try {
            $params = $request->all();
            $rule = [
                'ids' => "required",
                'action' => "required|integer",
            ];
            $returnMsg = AdmController::validatorRule($rule, $params);

            if ($returnMsg !== true) {
                throw new \UnexpectedValueException($returnMsg);
            }
            $basicIds = $params['ids'];
            foreach ($basicIds as $id) {
                $where['id'] = $id;
                //获取原全部图片
                $imgs = mWikiBasic::get('imgs', $where);
                if (!$imgs) {
                    throw new \UnexpectedValueException("不存在或已删除");
                }
                $imgs = json_decode($imgs, true);
                $status = WikiBasic::WIKI_BASIC_IMAGE_STATUS_DONE;
                //组合图片状态
                foreach ($imgs as $k => $img) {
                    $imgs[$k]['status'] = $status;
                }
                $data['cover_img'] = '';
                //查找新的首图
                foreach ($imgs as $img) {
                    $data['cover_img'] = $img['img'];
                    break;
                }
                $data['imgs'] = json_encode($imgs);
                $data['imgs_status'] = WikiBasic::IMGS_STATUS_DONE;
                WikiBasic::updateData($where, $data);
            }
            $res_msg = [
                'title' => '操作成功',
                'code' => 200
            ];
        } catch (\UnexpectedValueException $e) {
            $res_msg = [
                'title' => $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        } catch (\Exception $e) {
            $res_msg = [
                'title' => '操作失败,',
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($res_msg);
    }

    private function changeScript()
    {
        return <<<SCRIPT
         let url = '/admin/brand/wiki/img/audit_images'
         $("#access").click(
             function() {
             id = $("#access").attr("val")
             type = $("#access").attr("action")
             params = {id:id,type:type}
             console.log(params)
                $.post(url, params , function (result) {
                  if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
                 });

         });

         $("#unpass").click(
             function() {
             id = $("#unpass").attr("val")
             type = $("#unpass").attr("action")
             params = {id:id,type:type}
                $.post(url, params , function (result) {
                  if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
                 });

         });
        SCRIPT;
    }
}